package trees.parsers;

import java.io.{File}
import java.util.Scanner;

object NewickParser {
  
	//Cleans the string from all line endings, branch lengths and consensus scores
	def cleanNewickTreeString(treeStr: String) = {
		val treeStrNoLineEndings = treeStr.replaceAll("(\\r|\\n)","")
		var cleanStr = ""
		var add = true
		for (char <- treeStrNoLineEndings){
			if (char == ':')
				add = false
			if (char == ')' || char == ',' || char == ';')
				add = true
			if (add){
				cleanStr += char
				//println(char)
			}
		}
		cleanStr
	}
	
 
	//Strips taxon names from a cleaned newick tree string and returns a List[String]
	// of names
	def getTaxNamesFromCleanNewickString(cleanTreeString: String) = {
	  var names = List[String]()
	  var tree = ""
	  var name = ""
		for (char <- cleanTreeString){
			if (char == '(' || char == ';'){
				tree += char
			}else{
				if (char == ')' || char == ','){
				  	if (name.length > 0){
				  		names = names.::(name)
				  		name = ""
				  	}
					tree += char
				}
				else{
					name += char.toString
				}
			}
		}
		names
	}
 
	//Public method to get the tree string from a Newick file
	//The string is whitout line endings and all branch lenght and consensus data is removed
	def readNewickStringFromFile(fileName: String) = {
                val scanner = new Scanner(new File(fileName))
                var list = List[TreeData]()
                var line = ""
                var treeString = ""
                while ( scanner.hasNextLine() ){
                    line = scanner.nextLine()
                    if (line.endsWith(";")){
                        treeString += line
                        var cleanTreeString = cleanNewickTreeString(treeString)
                        var names = getTaxNamesFromCleanNewickString(cleanTreeString)
                        list = TreeData("NoName", cleanTreeString, names, 0, true) :: list
                    }else{
                        treeString += line
                    }
                }
                scanner.close()
                list
	}

}